﻿using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json;
using Volo.Abp.MultiTenancy;
using Volo.Abp.SettingManagement;
using Joy.Erp.BasicArchives.Core.UniqueCodes;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;

namespace Joy.Erp.BasicArchives.Core
{
    [Authorize]
    public class UniqueCodeSettingAppService : BasicArchivesAppService, IUniqueCodeSettingAppService
    {
        protected ISettingManager SettingManager => LazyServiceProvider.LazyGetRequiredService<ISettingManager>();
        protected UniqueCodeOptions UniqueCodeOptions => LazyServiceProvider.LazyGetRequiredService<IOptions<UniqueCodeOptions>>().Value;

        public async Task<UniqueCodeSettingDto> GetAsync(string key)
        {
            var settingValue = await SettingProvider.GetOrNullAsync(key);

            if (CurrentTenant.IsAvailable)
            {
                settingValue = await SettingManager.GetOrNullForTenantAsync(key, CurrentTenant.GetId(), false);
            }

            var settingValueObj = JsonConvert.DeserializeObject<UniqueCodeConfigrationObject>(settingValue);
            var segmentConfigrations = new List<SegmentConfigrationDto>();
            foreach (var segmentConfigration in settingValueObj.SegmentConfigrations)
            {
                var segmentConfigrationArray = segmentConfigration.Split("::");
                var segmentKey = segmentConfigrationArray[0];
                var configration = segmentConfigrationArray[1];

                segmentConfigrations.Add(new SegmentConfigrationDto { Key = segmentKey, Configration = configration });
            }
            var settingDto = new UniqueCodeSettingDto
            {
                AutoCode = settingValueObj.AutoCode,
                SegmentConfigrations = segmentConfigrations
            };

            return settingDto;
        }

        public async Task UpdateAsync(string key, UniqueCodeSettingDto value)
        {
            var settingValueObj = new UniqueCodeConfigrationObject();
            settingValueObj.AutoCode = value.AutoCode;

            foreach (var segmentConfigration in value.SegmentConfigrations)
            {
                settingValueObj.SegmentConfigrations.Add($"{segmentConfigration.Key}::{segmentConfigration.Configration}");
            }

            await SettingManager.SetForTenantOrGlobalAsync(CurrentTenant.Id, key, JsonConvert.SerializeObject(settingValueObj));
        }

        public async Task<UniqueCodeOptionsDto> GetOptionsAsync()
        {
            var dto = new UniqueCodeOptionsDto()
            {
                AllKeys = UniqueCodeOptions.GetAllKeys(),
            };

            return await Task.FromResult(dto);
        }
    }
}
